package com.jinyou.utils.common;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 定义Json字符串的静态方法
 * 
 * @author Jahnke 2016年3月5日11:13:32
 * 
 */
public class JsonUtils {

	/**
	 * 将Json转成List<Map>格式
	 * 
	 * @param json
	 * @param list
	 * @return 2016年3月5日11:14:22 Jahnke
	 */
	public static List<HashMap<String, Object>> jsonToListmap(String json) {
		if(ValidateUtil.isNull(json) || json.equals("[]")){
			return null;
		}
		JSONArray jsonArray = JSONArray.fromObject(json);
		List<HashMap<String, Object>> list = handleJSONArray(jsonArray);
		return list;
	}

	public static List<HashMap<String, String>> getList(JSONArray array) {
		if (array != null && array.size() > 0) {
			List<HashMap<String, String>> rsList = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject ob = array.getJSONObject(i);
				HashMap<String, String> map = new HashMap<String, String>();
				for (Iterator<?> it = ob.keys(); it.hasNext();) {
					String key = (String) it.next();
					String value = ob.getString(key);
					map.put(key, value);
				}
				rsList.add(map);
			}
			return rsList;
		}
		return null;
	}

	private static List<HashMap<String, Object>> handleJSONArray(
			JSONArray jsonArray) {
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = (JSONObject) jsonArray.get(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			Iterator<?> it = jsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = jsonObject.get(key);
				map.put(key, value == null ? "" : value);
			}
			list.add(map);
		}
		return list;
	}

}
